/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.controller;


import io.renren.common.annotation.SysLog;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sys.dao.SysUserRoleDao;
import io.renren.modules.sys.entity.DoctorEntity;
import io.renren.modules.sys.entity.SysRoleEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.DoctorService;
import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.shiro.ShiroUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;

	@Autowired
	private DoctorService doctorService;

	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	@Autowired
	private SysRoleService sysRoleService;
	
	/**
	 * 所有用户列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:user:list")
	public R list(@RequestParam Map<String, Object> params){
		PageUtils page = sysUserService.queryPage(params);

		return R.ok().put("page", page);
	}
	
	/**
	 * 获取登录的用户信息
	 */
	@RequestMapping("/info")
	public R info(){
		return R.ok().put("user", getUser());
	}
	
	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@RequestMapping("/password")
	public R password(String password, String newPassword){
		Assert.isBlank(newPassword, "新密码不为能空");

		//原密码
		password = ShiroUtils.sha256(password, getUser().getSalt());
		//新密码
		newPassword = ShiroUtils.sha256(newPassword, getUser().getSalt());
				
		//更新密码
		boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
		if(!flag){
			return R.error("原密码不正确");
		}
		
		return R.ok();
	}
	
	/**
	 * 用户信息
	 */
	@RequestMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	public R info(@PathVariable("userId") Long userId){
		SysUserEntity user = sysUserService.getById(userId);
		
		//获取用户所属的角色列表
		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		user.setRoleIdList(roleIdList);
		
		return R.ok().put("user", user);
	}
	
	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@RequestMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R save(@RequestBody String str){
		JSONObject json = JSONObject.fromObject(str);
		SysUserEntity user = new SysUserEntity();
		user.setUsername(json.getString("username"));
		user.setPassword(json.getString("password"));
		user.setDeptId(json.getLong("deptId"));
		user.setEmail(json.getString("email"));
		user.setHeadimg(json.getString("headimg"));
		user.setMobile(json.get("mobile")==null?"":json.getString("mobile"));

		List<Long> list = new ArrayList<Long>();
		JSONArray array = json.getJSONArray("roleIdList");
		for(int i=0;i<array.size();i++){
			list.add(Long.valueOf(array.get(i).toString()));
		}
		user.setRoleIdList(list);
		user.setStatus(json.getInt("status"));

		ValidatorUtils.validateEntity(user, AddGroup.class);
		
		sysUserService.saveUser(user);

		JSONObject jsonObject = json.getJSONObject("doctor");
		DoctorEntity doctor = new DoctorEntity();
		doctor.setFavorablerate("100%");
		doctor.setName(jsonObject.getString("name"));
		doctor.setAddress(jsonObject.get("address")==null?"":jsonObject.getString("address"));
		doctor.setLongitude(jsonObject.get("longitude")==null?"":jsonObject.getString("longitude"));
		doctor.setLatitude(jsonObject.get("latitude")==null?"":jsonObject.getString("latitude"));
		doctor.setHospital(jsonObject.get("hospital")==null?"":jsonObject.getString("hospital"));
		doctor.setUserid(Integer.parseInt(user.getUserId().toString()));
		doctorService.save(doctor);
		
		return R.ok();
	}
	
	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@RequestMapping("/update")
	@RequiresPermissions("sys:user:update")
	public R update(@RequestBody String str){

		JSONObject json = JSONObject.fromObject(str);
		SysUserEntity user = sysUserService.getById(json.getInt("userId"));
		user.setUsername(json.getString("username"));
		user.setDeptId(json.getLong("deptId"));
		user.setEmail(json.getString("email"));
		user.setHeadimg(json.getString("headimg"));
		user.setMobile(json.get("mobile")==null?"":json.getString("mobile"));

		List<Long> list = new ArrayList<Long>();
		JSONArray array = json.getJSONArray("roleIdList");
		for(int i=0;i<array.size();i++){
			list.add(Long.valueOf(array.get(i).toString()));
		}
		user.setRoleIdList(list);
		user.setStatus(json.getInt("status"));

		ValidatorUtils.validateEntity(user, UpdateGroup.class);

		sysUserService.update(user);

		JSONObject jsonObject = json.getJSONObject("doctor");
		DoctorEntity doctor = doctorService.getDoctorByUserid(json.getInt("userId"));
		doctor.setName(jsonObject.getString("name"));
		doctor.setAddress(jsonObject.get("address")==null?"":jsonObject.getString("address"));
		doctor.setLongitude(jsonObject.get("longitude")==null?"":jsonObject.getString("longitude"));
		doctor.setLatitude(jsonObject.get("latitude")==null?"":jsonObject.getString("latitude"));
		doctor.setHospital(jsonObject.get("hospital")==null?"":jsonObject.getString("hospital"));
		doctorService.saveOrUpdate(doctor);
		return R.ok();
	}
	
	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@RequestMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long[] userIds){
		if(ArrayUtils.contains(userIds, 1L)){
			return R.error("系统管理员不能删除");
		}
		
		if(ArrayUtils.contains(userIds, getUserId())){
			return R.error("当前用户不能删除");
		}

		for(int i=0;i<userIds.length;i++){
			DoctorEntity  entity = doctorService.getDoctorByUserid(Integer.parseInt(userIds[i].toString()));
			doctorService.removeById(entity.getId());
		}

		sysUserService.removeByIds(Arrays.asList(userIds));
		
		return R.ok();
	}

	/**
	 * 查询当前登录用户角色
	 */
	@RequestMapping("/getRoleLoginUser")
	@RequiresPermissions("sys:role:getRoleLoginUser")
	public R getRoleLoginUser(){
		SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
		Long roleId = sysUserRoleDao.queryRoleId(user.getUserId());
		SysRoleEntity role = sysRoleService.getById(roleId);
		return R.ok().put("role",role);
	}
}
